package com.zzyl.service.impl;

import cn.hutool.core.util.StrUtil;
import com.zzyl.constant.Constants;
import com.zzyl.dto.UserLoginRequestDto;
import com.zzyl.entity.Member;
import com.zzyl.mapper.MemberMapper;
import com.zzyl.properties.JwtProperties;
import com.zzyl.service.MemberService;
import com.zzyl.service.WechatService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.RandomNicknameGenerator;
import com.zzyl.vo.LoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class MemberServiceImpl implements MemberService {

    @Autowired
    private WechatService wechatService;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {

        //1.调用微信接口获取openid
        String openid = wechatService.getOpenid(userLoginRequestDto.getCode());
        //2.根据openid查询会员表,判断当前用户是否存在
        Member member = memberMapper.selectByOpenid(openid);
        //3.判断会员是否存在,不存在则自动注册
        if (member==null) {
            member = new Member();
            member.setOpenId(openid);
            log.info("会员是{}", member);
        }
        //4.获取用户手机号
        String phone = wechatService.getPhone(userLoginRequestDto.getPhoneCode());
        log.info("电话号码为:{}",phone);
        //5.新增或更新用户信息
        saveOrUpdate(member, phone);
        //6.生成登录成功凭据
        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.JWT_USERID, member.getId());
        claims.put(Constants.JWT_USERNAME, member.getName());
        String jwt = JwtUtil.createJWT(jwtProperties.getBase64EncodedSecretKey(), jwtProperties.getTtl(), claims);
        return LoginVo.builder().token(jwt).nickName(member.getName()).build();
    }

    private void saveOrUpdate(Member member, String phone) {
        if (member.getId() == null) {  //新增
            member.setName(RandomNicknameGenerator.generateRandomNickname()); //用户昵称
            member.setPhone(phone);
            memberMapper.insertMember(member);
        } else {
            if(!StrUtil.equals(member.getPhone(),phone)){
                member.setPhone(phone);
                memberMapper.updateMember(member);
            }
        }
    }
}
